-module(youtube).
-export([fetch_sequential/0, fetch_parallel/0]).
-include_lib("xmerl/include/xmerl.hrl").

get_feed() ->
	{ ok, {_Status, _Headers, Body }} = 
		http:request("http://gdata.youtube.com/feeds/standardfeeds/most_viewed"),
	{ Xml, _Rest } = xmerl_scan:string(Body),
		xmerl_xpath:string("//author/name/text()", Xml).
 
get_user_profile(User) ->
	#xmlText{value = Name} = User,
	URL = "http://gdata.youtube.com/feeds/users/" ++ Name,
	{ ok, {_Status, _Headers, Body} } = http:request(URL),
	{ Xml, _Rest } = xmerl_scan:string(Body),
	[#xmlText{value = Id}] = xmerl_xpath:string("//id/text()", Xml),
	[#xmlText{value = Published}] = xmerl_xpath:string("//published/text()", Xml),
	{ Name, Id, Published }.
    
fetch_sequential() ->
	lists:map(fun get_user_profile/1, get_feed()).

fetch_parallel() ->	
	inets:start(),
	Users = get_feed(),
	lists:foreach(fun background_fetch/1, Users),
    gather_results(Users).

background_fetch(User) ->
	ParentPID = self(),
	spawn(fun() -> ParentPID ! { ok, get_user_profile(User) } end).

gather_results(Users) ->
	lists:map(fun(_) ->
		receive 
			{ ok, Anything } -> Anything
		end
    end, Users).